package com.dede.net_speed_monitor.service;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Icon;
import android.net.ConnectivityManager;
import android.net.TrafficStats;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.preference.PreferenceManager;
import android.service.quicksettings.Tile;
import android.service.quicksettings.TileService;
import android.support.annotation.RequiresApi;
import android.support.v4.content.LocalBroadcastManager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.format.Formatter;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.util.Log;
import android.widget.Toast;

import com.dede.net_speed_monitor.R;
import com.dede.net_speed_monitor.activity.SettingActivity;
import com.dede.net_speed_monitor.broadcast.NetChangeBroadcastReceiver;
import com.dede.net_speed_monitor.config.Config;
import com.dede.net_speed_monitor.util.NetUtil;
import com.dede.net_speed_monitor.util.UIUtil;

import static android.view.WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
import static com.dede.net_speed_monitor.util.NetUtil.getNetState;

/**
 * Created by hsh on 2017/3/21 021 下午 04:32.
 */
@RequiresApi(api = Build.VERSION_CODES.N)
public class NetTileService extends TileService implements NetChangeBroadcastReceiver.OnNetChangeListener {

    private final String TAG = NetTileService.class.getSimpleName();
    private static final int REFRESH_MSG = 1;

    private long mInterval;//更新间隔
    private int mTextColor;//字体颜色
    private int mTextSize;
    private int mTextStyle;

    private SharedPreferences mSp;

    private long rxBytes;
    private long preRxBytes;
    private long mDownloadSpeed;

    private NetChangeBroadcastReceiver mNetChangeBroadcastReceiver;

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == REFRESH_MSG) {
                rxBytes = TrafficStats.getTotalRxBytes();
                mDownloadSpeed = (long) ((rxBytes - preRxBytes) * 1d / mInterval * 1000 + .5d);
                preRxBytes = rxBytes;
                Log.i(TAG, "handleMessage: " + mDownloadSpeed);

                Tile qsTile = getQsTile();

                String downSpeed;
                downSpeed = "" + Formatter.formatFileSize(getBaseContext(), mDownloadSpeed) + "/s";

                SpannableString downSpeedStr = new SpannableString(downSpeed);
                ForegroundColorSpan span1 = new ForegroundColorSpan(mTextColor);
                downSpeedStr.setSpan(span1, 0, downSpeed.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                StyleSpan span2;
                switch (mTextStyle) {
                    case Config.TextStyle.NORMAL:
                        span2 = new StyleSpan(Typeface.NORMAL);
                        break;
                    case Config.TextStyle.BOLD:
                        span2 = new StyleSpan(Typeface.BOLD);
                        break;
                    case Config.TextStyle.ITALIC:
                        span2 = new StyleSpan(Typeface.ITALIC);
                        break;
                    case Config.TextStyle.ALL:
                        span2 = new StyleSpan(Typeface.BOLD_ITALIC);
                        break;
                    default:
                        span2 = new StyleSpan(Typeface.NORMAL);
                        break;
                }
                downSpeedStr.setSpan(span2, 0, downSpeed.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                AbsoluteSizeSpan span3 = new AbsoluteSizeSpan(mTextSize);
                downSpeedStr.setSpan(span3, 0, downSpeed.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

                qsTile.setLabel(downSpeedStr);
                qsTile.updateTile();
                mHandler.sendEmptyMessageDelayed(REFRESH_MSG, mInterval);
            }
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "onCreate: ");
//        mSp = getSharedPreferences(Config.SP_Key.SP_NAME_KEY, Context.MODE_PRIVATE);
        mSp = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        loadSetting();
    }

    @Override
    public void onTileAdded() {
        super.onTileAdded();
        Log.i(TAG, "onTileAdded: ");
    }

    @Override
    public void onStartListening() {
        super.onStartListening();
        Log.i(TAG, "onStartListening: ");
        if (shouldReload) {
            loadSetting();
            shouldReload = false;
        }
        if (mNetChangeBroadcastReceiver == null) {
            mNetChangeBroadcastReceiver = new NetChangeBroadcastReceiver();
            IntentFilter filter = new IntentFilter();
            filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); // 添加接收网络连接状态改变的Action
            registerReceiver(mNetChangeBroadcastReceiver, filter);
            mNetChangeBroadcastReceiver.setNetChangeListener(this);
        }

        int netState = getNetState(getBaseContext());
        if (netState != NetUtil.NONE) {
            rxBytes = TrafficStats.getTotalRxBytes();
            preRxBytes = rxBytes;
            mHandler.sendEmptyMessage(REFRESH_MSG);
        }

        //发送广播，移除通知
        boolean notifyAutoRemove = mSp.getBoolean(getString(R.string.notify_auto_remove_key), true);
        if (notifyAutoRemove) {
            Intent intent = new Intent().setAction(NetMonitorService.TileChangeListenerReceiver.TITLE_CHANGE_ACTION)
                    .putExtra("state", true);
            LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(getApplicationContext());
            broadcastManager.sendBroadcast(intent);
        }
    }

    /**
     * 加载设置
     */
    private void loadSetting() {
        mInterval = Long.valueOf(mSp.getString(getString(R.string.tile_update_interval_key), "1000"));
        mTextColor = Color.parseColor("#" + mSp.getString(getString(R.string.tile_text_color_key), "FFCCCCCC"));
        mTextSize = UIUtil.sp2pxInt(getBaseContext(), Integer.valueOf(mSp.getString(getString(R.string.tile_text_size_key), "12")));
        mTextStyle = Integer.valueOf(mSp.getString(getString(R.string.tile_text_style_key), "0"));
    }

    @Override
    public void onStopListening() {
        super.onStopListening();
        if (mNetChangeBroadcastReceiver != null) {
            unregisterReceiver(mNetChangeBroadcastReceiver);
            mNetChangeBroadcastReceiver = null;
        }
        mHandler.removeCallbacksAndMessages(null);

        boolean isFirst = mSp.getBoolean(Config.SP_Key.TILE_IS_FIRST_ADD_KEY, Config.DefaultValue.TILE_IS_FIRST_ADD);
        Log.i(TAG, "onStopListening: isFirst:" + isFirst);

        if (isFirst) {
            Toast.makeText(this, "点击通知栏快速设置即可打开设置页面", Toast.LENGTH_LONG).show();
            Intent intent = new Intent(getBaseContext(), SettingActivity.class);
            startActivityAndCollapse(intent);
            mSp.edit().putBoolean(Config.SP_Key.TILE_IS_FIRST_ADD_KEY, false).commit();
        }
        boolean notifyAutoRemove = mSp.getBoolean(getString(R.string.notify_auto_remove_key), true);
        if (notifyAutoRemove) {
            //发送广播，开启通知
            Intent intent = new Intent().setAction(NetMonitorService.TileChangeListenerReceiver.TITLE_CHANGE_ACTION)
                    .putExtra("state", false);
            LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(getApplicationContext());
            broadcastManager.sendBroadcast(intent);
        }
    }

    @Override
    public void onTileRemoved() {
        super.onTileRemoved();
        Log.i(TAG, "onTileRemoved: ");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy: ");
    }

    @Override
    public void onClick() {
        super.onClick();
        Log.i(TAG, "onClick: ");
//        Tile qsTile = getQsTile();
//        if (qsTile.getState() == Tile.STATE_INACTIVE
//                && NetUtil.getNetState(getBaseContext()) != NetUtil.NONE) {
//            qsTile.setState(Tile.STATE_ACTIVE);
//            qsTile.updateTile();
//        }

        Intent intent = new Intent(getBaseContext(), SettingActivity.class);
        if (isLocked()) {
            intent.addFlags(FLAG_SHOW_WHEN_LOCKED);
        }
        boolean showIcon = mSp.getBoolean(Config.SP_Key.ICON_STATE_KEY, Config.DefaultValue.ICON_STATE);
        if (showIcon) {
            Log.i(TAG, "onClick: 图标为显示状态");
        } else {
            Log.i(TAG, "onClick: 图标为隐藏状态");
        }
        startActivityAndCollapse(intent);
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG, "onBind: ");
        return super.onBind(intent);
    }

    @Override
    public void onNetChange(@NetUtil.NetType int state) {
        Tile qsTile = getQsTile();
        mHandler.removeCallbacksAndMessages(null);
        switch (state) {
            case NetUtil.WIFI:
                qsTile.setIcon(Icon.createWithResource(getBaseContext(), R.drawable.ic_network_wifi_3));
                qsTile.setState(Tile.STATE_ACTIVE);
                mHandler.sendEmptyMessage(REFRESH_MSG);
                break;
            case NetUtil.MOBILE:
            case NetUtil.MOBILE_2G:
            case NetUtil.MOBILE_3G:
            case NetUtil.MOBILE_4G://添加移动网络状态,需添加图标
                qsTile.setIcon(Icon.createWithResource(getBaseContext(), R.drawable.ic_network_mobile_2));
                qsTile.setState(Tile.STATE_ACTIVE);
                mHandler.sendEmptyMessage(REFRESH_MSG);
                break;
            case NetUtil.NONE:
                qsTile.setIcon(Icon.createWithResource(getBaseContext(), R.drawable.ic_network_none));
                qsTile.setLabel(getResources().getString(R.string.none_net));
                qsTile.setState(Tile.STATE_INACTIVE);
                break;
            default:
                qsTile.setIcon(Icon.createWithResource(getBaseContext(), R.drawable.ic_network_none));
                qsTile.setLabel(getResources().getString(R.string.none_net));
                qsTile.setState(Tile.STATE_INACTIVE);
                break;
        }
        qsTile.updateTile();
    }

    private static boolean shouldReload = false;//是否需要重新加载设置

    /**
     * 设置改变的广播接受者
     */
    public static class SettingChangeBroadcastReceiver extends BroadcastReceiver {

        public static final String ACTION_SETTING_CHANGE = "setting_change";
        public final String TAG = SettingChangeBroadcastReceiver.class.getSimpleName();

        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i(TAG, "onReceive: " + intent.getAction());
            shouldReload = true;
        }
    }
}
